const jwt = require('../lib/Jwt')
// 定义跳过验证的中间件
const escape = [
    '/oauth/code',
    '/oauth/token',
    '/oauth/authorize'   
]
module.exports = async function (ctx, next) {
    // 跳过不需要签名的接口
    let path = ctx.request.path
    if (escape.includes(path)) {
        return next()
    }
    const authorization = ctx.req.headers.Authorization || ctx.req.headers.authorization
    const bearer = /^Bearer .+/
    if ( !bearer.test( authorization ) ) ctx.throw('Token 格式不配备', 200)
    const token = authorization.replace( /^Bearer /, '' )
    
    let decode = await jwt.verify(token)
    if (decode) {
        let time = Date.now()
        let iat = decode.iat            //创建时间
        let exp = decode.exp * 1000     // 有效期
        // 判断token 过期
        if (time > exp) {
            ctx.throw('Token 已过期')
        }
        ctx.oauth = {}
        ctx.oauth.access_token = token  //jwt        
        ctx.oauth.client_id = decode.data.client
        ctx.oauth.user_id = decode.data.user
        /** grant_type=authorization_code 时存在 **/
        if ('code' in decode.data) {
            ctx.oauth.code_id = decode.data.code
        }
        ctx.oauth.access_token_id = decode.data.access_token
    } else {
        ctx.throw('非法Token')
    }
    return next()
}